package team.scau.laboratory_repair.common.base;

import com.querydsl.core.types.Order;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import team.scau.laboratory_repair.common.constant.ConstantWebContext;
import team.scau.laboratory_repair.common.constant.ShiroConstant;
import team.scau.laboratory_repair.common.page.ConstantSplitPage;
import team.scau.laboratory_repair.common.page.MyPage;
import team.scau.laboratory_repair.common.utils.QDSLTool;
import team.scau.laboratory_repair.common.utils.spring.StringToTimeConverter;
import team.scau.laboratory_repair.config.WebConf;
import team.scau.laboratory_repair.modules.po.User;
import team.scau.laboratory_repair.modules.po.WechatUser;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.security.Timestamp;
import java.util.Date;
import java.util.LinkedHashMap;

/**
 * @author 30254
 * creadtedate:2018/8/19
 */
@CommonsLog
public abstract class BaseController {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    @Autowired
    protected HttpSession session;

    @Autowired
    protected ServletContext application;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : text.trim());
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        //String 转 Timestamp
        binder.registerCustomEditor(Timestamp.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String value) {
                setValue(StringToTimeConverter.convert(value));
            }
        });
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                Date date;
                try {
                    System.out.println("===日期转换==");
                    date = DateUtils.parseDate(text, "yyyy-MM-dd", "yyyy-MM-dd hh:mm:ss");
                } catch (Exception e) {
                    date = new Date();
                }
                setValue(date);
            }
        });

    }

    protected String getPara(String param){
        String value = request.getParameter(param);
        if (null != value && !value.isEmpty()) {
            try {
                return URLDecoder.decode(value.replaceAll("%", "%25"), "UTF-8").trim();
            } catch (UnsupportedEncodingException e) {
                log.error("decode异常：" + value);
                return value;
            }
        }
        return value;
    }

    protected MyPage getPage(Class<?> qClazz){
        int current;
        if(request.getParameter(ConstantWebContext.REQUEST_PAGE_NUMBER) != null) {
            current = Integer.parseInt(getPara(ConstantWebContext.REQUEST_PAGE_NUMBER));
        }else if (request.getParameter(ConstantWebContext.REQUEST_PAGE) != null){
            current = Integer.parseInt(getPara(ConstantWebContext.REQUEST_PAGE));
        }else{
            current = ConstantSplitPage.DEFAULT_PAGE_NUMBER;
        }
        int size;
        if(request.getParameter(ConstantWebContext.REQUEST_PAGE_SIZE) != null) {
            size = Integer.parseInt(getPara(ConstantWebContext.REQUEST_PAGE_SIZE));
        }else if (request.getParameter(ConstantWebContext.REQUEST_LIMIT) != null){
            size = Integer.parseInt(getPara(ConstantWebContext.REQUEST_LIMIT));
        }else{
            size = ConstantSplitPage.DEFAULT_PAGE_SIZE;
        }
        String orderField = BaseModel.UPDATETIME;
        if(StringUtils.isNotEmpty(request.getParameter(ConstantWebContext.REQUEST_ORDER_COLUNM))) {
            orderField = getPara(ConstantWebContext.REQUEST_ORDER_COLUNM);
        }
        String orderMode = getPara(ConstantWebContext.REQUEST_ORDER_MODE);
        Order order = "asc".equals(orderMode) ? Order.ASC :Order.DESC;
        LinkedHashMap<String, Order> map = new LinkedHashMap<>();
        map.put(orderField, order);

        return new MyPage(current - 1, size, QDSLTool.warpSort(qClazz, map));
    }

    /**
     * 重定向至地址 url
     * @param url 请求地址
     * @return
     */
    protected String redirectTo(String url) {
        StringBuffer rto = new StringBuffer("redirect:");
        rto.append(url);
        return rto.toString();
    }

    protected void addCookie(String domain, String path, boolean isHttpOnly,
                             String name, String value, int maxAge){
        Cookie cookie = new Cookie(name, value);

        // 所在域：比如a1.4bu4.com 和 a2.4bu4.com 共享cookie
        if(null != domain && !domain.isEmpty()){
            cookie.setDomain(domain);
        }

        // 设置cookie所在路径
        cookie.setPath("/");
        if(null != path && !path.isEmpty()){
            cookie.setPath(path);
        }

        // 是否只读
        try {
            cookie.setHttpOnly(isHttpOnly);
        } catch (Exception e) {
            log.error("servlet容器版本太低，servlet3.0以前不支持设置cookie只读" + e.getMessage());
        }

        // 设置cookie的过期时间
        if (maxAge > 0){
            cookie.setMaxAge(maxAge);
        }

        // 添加cookie
        response.addCookie(cookie);
    }

    /**
     * 上传文件的路径
     *
     * @param request
     * @return
     * @throws MalformedURLException
     */
    protected String getDocRoot(HttpServletRequest request) throws MalformedURLException {
//        String path = request.getServletContext().getRealPath("/") + "upload";
        String path = WebConf.UPLOAD_PATH + File.separator;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }

    /**
     * 项目根路径
     * @return /sms/upload
     * @throws MalformedURLException
     */
    protected String getUploadRoot() throws MalformedURLException {
        return "/upload";
    }

    protected User getCUser(){
        return (User) session.getAttribute(ConstantWebContext.REQUEST_CUSER);
    }

    protected WechatUser getWUser(){
        return (WechatUser) session.getAttribute(ShiroConstant.REQUEST_C_WECHAT_USER);
    }

    /**
     * 返回保存在session中的openid
     * @return
     */
    protected String getOpenId(){
        Object openid = session.getAttribute(ShiroConstant.REQUEST_OPEN_ID);
        if (openid instanceof String) {
            return (String)openid;
        }
        return null;
    }
}
